# Maestro is a music database search utility
# Copyright (C) 2010 Robert Mens
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

from __future__ import print_function
import os, os.path, string

directories = []
player_mode = u'cmd'
mode_cmd_play = [u'/usr/bin/audacious', u'@f']
mode_cmd_enqueue = [u'/usr/bin/audacious', u'-e',u'@f']
mpris_autostart = u'/usr/bin/audacious'
version = "dev-25062010"
mdb = None
player = None

def _select_player():
    global player_mode, player
    
    if player_mode == u'moc':
        try:
            import player_moc
            player = player_moc.MocPlayer()
            return
        except ImportError:
            print("Could not import moc, falling back to cmd")
            player_mode = u'cmd'

    if player_mode == u'cmd' or player == None:
        import player_cmd
        player = player_cmd.CmdPlayer()

def _split_option(option):
    idx = option.find(u'=')
    
    return (string.strip(option[:idx]), string.strip(option[idx+1:]))

def load(config_file = u"~/.maestro/config"):
    global directories, player_mode, mode_cmd_play, mode_cmd_enqueue, mpris_autostart

    try:
        config = open(os.path.abspath(os.path.expanduser(config_file)), 'r').readlines()
    except IOError:
        #write new config using defaults
        print("Configuration file not found, writing defaults to %s\n" % config_file)
        save(config_file)
        return

    current_section = ""
    section_lines = []
    sections = {}
    
    for line in config:
        line=line.decode().strip()
        if len(line) == 0: continue
        if line[0]==u'[': # sort out the blocks defined by [tags]
            idx = line.find(u']')
            if idx > 0:
                if current_section: sections[current_section] = section_lines
                section_lines = []
                current_section = line[1:idx]
        else:
            idx = line.find(';') #ignore comments
            if not idx == -1:
                if idx == 0: continue
                line = line[:idx]     
            section_lines.append(line)

    if current_section: sections[current_section] = section_lines

    if u'directories' in sections: directories = sections[u'directories']

    if u'player' in sections:
        for line in sections[u'player']:
            option = _split_option(line)
            if option[0] == u'mode': player_mode = option[1]
            elif option[0] == u'mode_cmd_play': mode_cmd_play = string.split(option[1])
            elif option[0] == u'mode_cmd_enqueue': mode_cmd_enqueue = string.split(option[1])
            elif option[0] == u'mpris_autostart': mpris_autostart = option[1]

    # not really config related but a convenient place.
    _select_player()

def save(config_file = u"~/.maestro/config"):
    global directories, player_mode, mode_cmd_play, mode_cmd_enqueue, mpris_autostart

    if config_file == u"~/.maestro/config" and not os.path.isdir(os.path.abspath(os.path.expanduser(u'~/.maestro'))):
        os.mkdir(os.path.abspath(os.path.expanduser(u'~/.maestro')))

    try:
        fp = open(os.path.abspath(os.path.expanduser(config_file)), 'w')

        fp.write(u'[player]\n')
        fp.write(u'; mode defines how an external player will be used, valid options are cmd, mpris\n')
        fp.write(u'mode = %s\n' % player_mode)
        fp.write(u'; mode_cmd_play and mode_cmd_enqueue respectively hold to command to execute for playing and enqueuing,\n; @f will be replaced by a single filename, or comma separated list whereas @m will be either a single or space separated list.\n')
        fp.write(u'mode_cmd_play = %s\n' % string.join(mode_cmd_play))
        fp.write(u'mode_cmd_enqueue = %s\n' % string.join(mode_cmd_enqueue))
        fp.write(u'; mpris_autostart defines the program that should be started if there are no mpris capable players available.\n')
        fp.write(u'mpris_autostart = %s\n' % mpris_autostart)
        fp.write(u'\n[directories]\n')
        fp.write(u'; list of directories to be scanned, one line each.\n')
        for directory in directories:
            fp.write(directory+'\n')
                
    except IOError:
        #write new config using defaults
        print("Unable to write config file: %s" % IOError.message)
        return

if __name__ == "__main__":
    load()
    print(directories)
    print(player_mode)
    print(mode_cmd_play)
    print(mode_cmd_enqueue)
    print(mpris_autostart)
    #save('~/.maestro/test')
    
    
